<?php
class ClassifyModel extends Model{
	public $table = 'classify';
	public $validate = array(
		array('cname',0,'分类名称不能为空',2,3),
		array('sort', 'num:1,65535', '排序字段必须为数字', 2, 3),
	);
	//添加分类
	public function add_cfy(){
		if(!$this->create()) return false;
		$cname = Q('post.cname');
		if($this->get_one_cfy(array('cname'=>$cname))){
			$this->error = $cname . '已经存在';
			return false;
		}
		return $this->add();
	}
	
	//获取所有分类数据
	public function get_all_cfy($where=Null,$needPage=FALSE){
		if($needPage){
		//分页类用法
		//总条数
		$total=$this->where($where)->count();
		//2表示每页取多少条，3表示页码的数量
		$pageObj = new Page($total,10,3);
		//显示分页，与验证码code一样，用show();
		$page = $pageObj->show();
		//分页类算出limit
		$limit = $pageObj->limit();
		//在使用分页类的时候一定要注意limit
		$data = $this->where($where)->limit($limit)->all();
		$data['page'] = $page;
		}else{
			$data = $this->order('sort ASC')->where($where)->all();
			$data = Data::tree($data,'cname','cid','pid');
		}
		return $data;
		
	}
	//获取一条分类数据
	public function get_one_cfy($where=Null,$field=Null){
		return $this->where($where)->field($field)->find();
	}
	//递归获得所有子集分类
	public function get_son($data,$cid){
		//组建临时数组
		$temp = array();
		//遍历$data
		foreach($data as $v){
			if($v['pid']==$cid){
				$temp[] = $v['cid'];
				$data = array_merge($temp,$this->get_son($data,$v['cid']));
			}
		}
		return $temp;
	}
	//获得所有子集
	public function get_son_cfy($cid){
		//获得所有数据
		$data = $this->all();
		return $this->get_son($data,$cid);
	}
	//删除
	public function del_cfy($cid){
		$data = $this->where(array('pid'=>$cid))->find();
		if($data){
			$this->error = "请先删除子分类";
			return false;
		}
		return $this->where(array('cid'=>$cid))->delete();
	}
	
		
	//修改操作
	//获得可更换选择的父级cid（排除自己和自己子集）
	public function get_change_cfy($cid){
		//获得与自己相关的数据
		$son = $this->get_son_cfy($cid);
		//把自己的子集放进去
		$son[]=$cid;
		//获取除子集以外的自己的数据
		$data = $this->get_all_data('cid not in(' . implode(',',$son) . ')');
		return $data;
	}
	//修改
	public function update_cfy($where=Null){
//		p($_POST);DIE;
		return $this->where($where)->save();
	}
	
	
}//end
